// pages/activityGoodsDetail/activityGoodsDetail.js

const host = require('../../config.js').host;
const network = require('../../utils/network.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: host,
    banlance: 0,
    baseUrl: "",
    detailDic: {},
    priceList: [],
    goodsId: '',
    activityGoodsPriceId: ''
  },
  getBanlance() {
    let that = this;
    network.requestGet(host + '/xcx/customer/getUserInfo', {}, res => {
      if (res.data.code == 200) {
        that.setData({
          banlance: res.data.data.balance,
        })
      }
    })
  },
  getDetail() {
    if(!this.data.goodsId){
      return;
    }
    let that = this;
    network.requestGet(host + '/xcx/activityGoods/get-info', {
      "goodsId": that.data.goodsId,
    }, res => {
      if (res.data.code == 200) {
        console.log('=======' + res)
        var arr = res.data.data.priceList
        for (const i in arr) {
          if (i == 0) {
            arr[i].checked = true
            that.setData({
              activityGoodsPriceId: arr[i].id
            })
          } else {
            arr[i].checked = false
          }

        }

        that.setData({
          detailDic: res.data.data,
          priceList: arr
        })
      } else {
        wx.showToast({
          title: res.data.msg ? res.data.msg : '请求失败',
          icon: "none",
          duration: 1200
        })
      }
    })
  },
  radioboxChange(e) {

    this.setData({
      activityGoodsPriceId: e.detail.value
    })
  },
  alertPayActionSheet() {
    let that = this;

    if (!that.data.activityGoodsPriceId) {
      wx.showToast({
        title: '请选择购买规格',
        icon: 'none'
      })
      return;
    }
    wx.showActionSheet({
      itemList: ['余额支付', '充值', '微信支付'],
      itemColor: '#000000',
      success: function (res) {
        console.log("点击了列表项：" + res.tapIndex)
        if (res.tapIndex == 0) {
          that.postPlayGameData(true);
        } else if (res.tapIndex == 1) {
          wx.navigateTo({
            url: '/pages/recharge/recharge',
          })
        } else if (res.tapIndex == 2) {
          that.postPlayGameData(false);
        }
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },

  // 根据卡位码支付
  postPlayGameData(isBanlance) {

    let that = this;
    var totalPrice = 0;
    that.data.priceList.forEach((item, index) => {
      if (item.id == that.data.activityGoodsPriceId) {
        totalPrice = item.goodsPrice;
      }
    });
    if (isBanlance) {
      if (totalPrice > that.data.banlance) {

        wx.showModal({
          title: '提示',
          content: '余额不足,是否去充值?',
          showCancel: true, //是否显示取消按钮
          cancelText: "取消", //默认是“取消”
          cancelColor: '#ff0000', //取消文字的颜色
          confirmText: "确定", //默认是“确定”
          confirmColor: '#000000', //确定文字的颜色
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定
              wx.navigateTo({
                url: '/pages/recharge/recharge',
              })
            }
          },
          fail: function (res) {},
          complete: function (res) {},
        })

        return;
      }
      wx.showModal({
        title: totalPrice > 0 ? '是否支付' + totalPrice : '是否支付' + 0 + '元?',
        content: '当前账户余额:' + that.data.banlance + '元',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#ff0000', //取消文字的颜色
        confirmText: "确定", //默认是“确定”
        confirmColor: '#000000', //确定文字的颜色
        success(res) {
          if (res.confirm) {
            wx.requestSubscribeMessage({
              tmplIds: ['Y8Yn83idPCEu7mCtlLwAWK5bu5uvQJisBdMls-M2CzI'],
              success(res) {}
            })
            network.requestPost(host + '/weiXinPayment/buy-activity-goods', {
              "activityGoodsId": that.data.goodsId,
              "activityGoodsPriceId": that.data.activityGoodsPriceId,
              "payType": isBanlance ? '1' : '0',
            }, res => {
              console.log("根据卡位码支付=" + res)
              if (res.data.code == 200) {


                wx.showToast({
                  title: '支付成功',
                  duration: 2000
                })


                setTimeout(() => {
                  // that.setData({
                  //   seatSnList:[],
                  //   customerPrizeIdList:[]
                  // })
                  that.getDetail()
                  that.getBanlance()
                }, 2000);
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '请求失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })


    } else {
      wx.showModal({
        title: totalPrice > 0 ? '是否使用微信支付' + totalPrice + '元?' : '是否使用微信支付' + 0 + '元?',
        content: '',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#ff0000', //取消文字的颜色
        confirmText: "确定", //默认是“确定”
        confirmColor: '#000000', //确定文字的颜色
        success(res) {
          if (res.confirm) {
            wx.requestSubscribeMessage({
              tmplIds: ['Y8Yn83idPCEu7mCtlLwAWK5bu5uvQJisBdMls-M2CzI'],
              success(res) {}
            })
            network.requestPost(host + '/weiXinPayment/buy-activity-goods', {
              "activityGoodsId": that.data.goodsId,
              "activityGoodsPriceId": that.data.activityGoodsPriceId,
              "payType": isBanlance ? '1' : '0',
            }, res => {
              console.log("根据卡位码支付=" + res)

              if (res.data.code == 200) {
                if (res.data.h5PayArgs) {
                  that.gotopay(res.data.h5PayArgs)
                } else {

                  wx.showToast({
                    title: '支付成功',
                    duration: 2000
                  })
                  setTimeout(() => {
                    // that.setData({
                    //   seatSnList:[],
                    //   customerPrizeIdList:[]
                    // })
                    that.getDetail()

                  }, 2000);

                }

              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '请求失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })


    }
  },
  gotopay(e) {
    let that = this;

    wx.requestPayment({
      signType: e.signType,
      timeStamp: e.timeStamp,
      nonceStr: e.nonceStr,
      package: e.package,
      paySign: e.paySign,
      success(res) {
        console.log('成功：' + res)


        wx.showToast({
          title: '支付成功',
          duration: 2000
        })


        setTimeout(() => {
          // that.setData({
          //   seatSnList:[],
          //   customerPrizeIdList:[]
          // })
          that.getDetail()

        }, 2000);
      },
      fail(res) {
        console.log('失败：' + res)
        wx.showToast({
          title: '支付失败',
          duration: 3000
        })
      },
      complete(res) {

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      baseUrl: host
    })
    console.log('----',options.goodsId);
    const scene = decodeURIComponent(options.scene)
    console.log('=====',options.scene);
    if(options.goodsId){
      this.setData({
        goodsId: options.goodsId
      })
    }else{ 
      var arr = scene.split('&') 

      for (const inde in arr) {
        console.log(arr[inde])
        var str = arr[inde]
        console.log(str)
        if (str.indexOf('goodsId=') == 0) {
          var newStr = str.replace(/goodsId=/, '')

          this.setData({
            goodsId: newStr
          })
        }
      }

    }
    this.getDetail();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBanlance();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})